package com.yunyike.interceptor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.model.User;
import com.yunyike.redis.JedisManager;
import com.yunyike.service.IUserService;
import com.yunyike.utils.CookieUtils;
import com.yunyike.wx.common.Oauth;
import com.yunyike.wx.common.WeiXinPropertiesUtil;
import com.yunyike.wx.utils.ServletUtils;

import net.sf.json.JSONObject;

/**
 * 登录拦截器 用来授权
 * 
 * @author wenjian
 *
 */
public class ActionInterceptor  extends HandlerInterceptorAdapter{

 private final Logger logger = LoggerFactory.getLogger(getClass());
 
 public final static String X_R = "X-Requested-With";
 public final static String X_R_VALUE = "XMLHttpRequest";
 
 @Autowired
 private IUserService userService;

 @Override
 public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
  
  // 获取当前用户
  /*User user = getCurrentUser(request);
  
  // 当前访问的地址
  String currenturl = request.getRequestURL()
    + (request.getQueryString() == null ? "" : ("?" + request.getQueryString()));
  logger.info("用户访问 currenturl:{}", currenturl);
  logger.info("用户Cookie ****** = "+request.getHeader("Cookie"));
  
  // 需要鉴权
  if(user == null){
   logger.info("需要鉴权");
   return doAuth(request, response, currenturl);
  }*/
  
  // 不需要鉴权
  return true;
 }

 private boolean doAuth(HttpServletRequest request, HttpServletResponse response, String currenturl)
   throws UnsupportedEncodingException, IOException, Exception {
  // 微信用户授权接口所需
  String code = request.getParameter("code");
  
  if(StringUtils.isBlank(code)){
   logger.info("用户请求的 code 没值,表示需要授权");
   // 没有调用授权接口，那么就调用它
   // 构造授权接口地址
   String redirectUrl = Oauth.getCode(URLEncoder.encode(currenturl, "utf-8"), true);
   // 直接跳转到目标url
   response.sendRedirect(redirectUrl);
   return false;
  }else{
   logger.info("用户请求的code 有值{}", code);
   // 看是否调用了授权接口，调用了的话在这里取得用户信息
   JSONObject jsonObject = JSONObject.fromObject(Oauth.getToken(code));
   String openid = jsonObject.getString("openid");
   logger.info("得到myOpenid is {}", openid);
   if(StringUtils.isNotBlank(openid)){
    logger.info("--->>拦截器 隐形注册...");
    // 隐形注册 + 登录
    addUserInvisible(openid, request, response);
    response.sendRedirect(currenturl);
    return false;
   }
   return true;
  }
 }
 
 private String addUserInvisible(String openId,HttpServletRequest request,
   HttpServletResponse response){
  
  User user = new User();
  user.setUserOpenId(openId);
  
  // 隐形注册
  int result = userService.addUserInvisible(user);
  
  if(result != 1){
   logger.info("controller add user end. but failed.");
   return ResponseConstant.FAILED;
  }
  
  logger.info("add user invisable result:{}.openId:{}",result,openId);
  
  // 登录
  logger.info("user login...");
  userService.login(openId, request, response);
  
  return ResponseConstant.SUCCESS;
 }
 
 /**
  * 获取当前登录的用户
  * @return
  */
 private User getCurrentUser(HttpServletRequest request) {
  // 获取用户的cookie
  Cookie cookie = CookieUtils.getCookie(request, CommonConstant.USER_KEY_COOKIE);
  
  if(cookie == null || StringUtils.isBlank(cookie.getValue())){
   return null;
  }
  // 根据cookie值获取用户
  User user = (User)JedisManager.getObject(cookie.getValue());
  
  if(user == null){
   return null;
  }
  
  logger.info("----->>current user:"+user);
  
  return user;
 }
}
